<template>
  <div class="login-container">
    <div class="content">
      <a-card :bordered="false" class="pl-5 pr-5">
        <div class="mb-8 mt-5 font-bold text-center text-xl">
          自由极客 Admin 管理系统
          <!-- <img
            src="@/assets/images/logo.png"
            alt=""
            srcset=""
            style="width: 200px; margin: 0 auto"
          /> -->
        </div>
        <a-tabs v-model:activeKey="activeKey">
          <a-tab-pane key="1" tab="账号登录">
            <a-form
              ref="formRef"
              :model="formState"
              :rules="rules"
              class="mt-4"
              v-if="activeKey == '1'"
            >
              <a-form-item ref="username" name="username">
                <a-input
                  v-model:value="formState.username"
                  placeholder="请输入用户名"
                  style="width: 100%"
                  allowClear
                >
                  <template #prefix> <user-outlined /> </template>
                </a-input>
              </a-form-item>
              <a-form-item ref="password" name="password">
                <a-input-password
                  v-model:value="formState.password"
                  type="password"
                  placeholder="请输入密码"
                >
                  <template #prefix>
                    <LockOutlined class="site-form-item-icon" />
                  </template>
                </a-input-password>
              </a-form-item>
              <a-form-item>
                <a-button
                  type="primary"
                  size="large"
                  @click="onSubmit(activeKey)"
                  class="mt-5"
                  style="width: 100%"
                  >登录</a-button
                >
              </a-form-item>
            </a-form>
          </a-tab-pane>
          <a-tab-pane key="2" tab="验证码登录">
            <a-form
              ref="formRef"
              :model="formState"
              :rules="rules"
              class="mt-4"
              v-if="activeKey == '2'"
            >
              <a-form-item ref="phone_number" name="phone_number">
                <a-input
                  v-model:value="formState.phone_number"
                  placeholder="请输入手机号"
                  style="width: 100%"
                  allowClear
                >
                  <template #prefix> <MobileOutlined /> </template>
                </a-input>
              </a-form-item>
              <a-form-item ref="verificationCode" name="verificationCode">
                <div class="flex items-center">
                  <a-input
                    v-model:value="formState.verificationCode"
                    placeholder="请输入验证码"
                    allowClear
                  >
                    <template #prefix>
                      <SafetyOutlined class="site-form-item-icon" />
                    </template>
                  </a-input>
                  <div class="ml-2 text-lg cursor-pointer">
                    <a-button
                      style="height: 36px"
                      @click="sendCode"
                      :disabled="sendCodeDisabled"
                      >{{ sendCodeText }}</a-button
                    >
                  </div>
                </div>
              </a-form-item>
              <a-form-item>
                <a-button
                  type="primary"
                  size="large"
                  @click="onSubmit(activeKey)"
                  class="mt-5"
                  style="width: 100%"
                  >登录</a-button
                >
              </a-form-item>
            </a-form>
          </a-tab-pane>
        </a-tabs>
      </a-card>
    </div>
  </div>
</template>
<script lang="ts" setup>
import {
  UserOutlined,
  LockOutlined,
  SafetyOutlined,
  MobileOutlined,
} from "@ant-design/icons-vue";
import { reactive, ref, toRaw } from "vue";
import type { UnwrapRef } from "vue";
import { useRouter } from "vue-router";
import type { Rule } from "ant-design-vue/es/form";
import useUserStore from "@/stores/modules/user";
import usePublicConfigStore from "../../stores/modules/public-config";
import {
  getDictionaryListApi,
  sendVerificationCodeApi,
  accountNumberLoginApi,
  getUserInfoApi,
  verifyCodeLoginApi,
} from "@/api/main";
import _ from "lodash";
import { message } from "ant-design-vue";
const userStore = useUserStore();
const publicConfigStore = usePublicConfigStore();
const router = useRouter();
const visible = ref<boolean>(true);
interface FormState {
  username: string;
  password: string;
  phone_number: string;
  verificationCode: string;
}
const formRef = ref();
const formState: UnwrapRef<FormState> = reactive({
  username: "",
  password: "",
  phone_number: "",
  verificationCode: "",
});
const activeKey = ref("1");
const rules: Record<string, Rule[]> = {
  username: [
    { required: true, message: "账号不能为空", trigger: "change" },
    { min: 4, max: 11, message: "账号长度为4-11个字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "密码不能为空", trigger: "change" },
    { min: 6, max: 20, message: "密码长度为6-20个字符", trigger: "blur" },
  ],
  phone_number: [
    { required: true, message: "手机号不能为空", trigger: "change" },
    {
      pattern:
        /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/,
      message: "请输入正确的手机号",
    },
  ],
  verificationCode: [
    { required: true, message: "验证码不能为空", trigger: "change" },
    { min: 6, max: 6, message: "请输入6位数验证码", trigger: "blur" },
  ],
};
// 获取字典列表
const getDictionaryList = () => {
  getDictionaryListApi({ page: 1, pageSize: 1000 }).then((response: any) => {
    console.log(response);
    if (response.code == 200) {
      publicConfigStore.dictionary = response.result.list;
    }
  });
};
getDictionaryList();

const onSubmit = (args: string) => {
  // 账号登录
  if (args == "1") {
    formRef.value
      .validate()
      .then(() => {
        accountNumberLoginApi({
          phone_number: formState.username,
          password: formState.password,
        }).then((response: any) => {
          if (response.code == 200) {
            message.success(response.message);
            userStore.token = response.result.token;
            userStore.loginStatus = true;
            getUserInfoApi().then((userinfo: any) => {
              console.log(userinfo);
              userStore.userInfo = userinfo.result;
              router.push("/");
            });
          } else {
            message.error(response.message);
          }
        });
      })
      .catch((error: any) => {
        console.log("error", error);
      });
  }
  // 验证码登录
  if (args == "2") {
    formRef.value
      .validate()
      .then(() => {
        verifyCodeLoginApi({
          phone_number: formState.phone_number,
          verification_code: formState.verificationCode,
        }).then((response: any) => {
          if (response.code == 200) {
            message.success(response.message);
            userStore.token = response.result.token;
            userStore.loginStatus = true;
            getUserInfoApi().then((userinfo: any) => {
              console.log(userinfo);
              userStore.userInfo = userinfo.result;
              router.push("/");
            });
          } else {
            message.error(response.message);
          }
        });
      })
      .catch((error: any) => {
        console.log("error", error);
      });
  }
};
const sendCodeText = ref("发送验证码");
const sendCodeDisabled = ref(false);
const countdown = ref(10);
const isCountingDown = ref(false);

const sendCode = _.debounce(() => {
  sendVerificationCodeApi({ phone_number: formState.phone_number }).then(
    (response: any) => {
      if (response.code == 200) {
        message.success(response.message);

        if (!isCountingDown.value) {
          isCountingDown.value = true;
          startCountdown();
        }
      } else {
        message.error(response.message);
      }
    }
  );
}, 500);

const startCountdown = () => {
  const interval = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--;
      sendCodeDisabled.value = true;
      sendCodeText.value = `${countdown.value}秒后重发`;
    } else {
      clearInterval(interval);
      sendCodeDisabled.value = false;
      countdown.value = 10;

      sendCodeText.value = "发送验证码";
    }
  }, 1000);
};
const resetForm = () => {
  formRef.value.resetFields();
};
</script>
<style scoped>
.login-container {
  width: 100%;
  height: 100vh;
  background: url("@/assets/images/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr.png")
    no-repeat center;
  background-size: 100% 100%;
}
/deep/ .ant-card {
  width: 500px;
  margin: 0 auto;
  /* margin-top: 200px; */
}
.content {
  position: fixed;
  top: calc(50% - 250px);
  left: calc(50% - 222px);
}
/deep/ .ant-input-affix-wrapper {
  height: 36px;
}
/deep/.anticon {
  vertical-align: 1px;
}
</style>
